const {exec} = require('../db/mysql')

// 获取文章的列表
const getList = (author, keyWord) => {
  let sql = 'select id,title,content,author,createtime from blogs where 1=1'
  if (author) {
    sql += ` and author='${author}'`
  }
  if (keyWord) {
    sql += ` and title like '%${keyWord}%'`
  }
  sql += ` order by createtime desc;`
  return exec(sql)
}

// 获取某文章的详情
const getDetail = (id) => {
  const sql = `select * from blogs where id=${id}`
  return exec(sql).then(rows => {
    return rows[0]
  })
}

// 新建博客
const newBlog = (blogData = {}) => {
  const {title, content, author} = blogData
  const createtime = Date.now()
  const sql = `insert into blogs (title,content,author,createtime) values ('${title}','${content}','${author}','${createtime}');`
  return exec(sql).then(insertData => {
    return {
      id: insertData.insertId
    }
  })
}

// 更新博客
const updateBlog = (id, blogData = {}) => {
  const {title, content} = blogData
  const createtime = Date.now()
  const sql = `UPDATE blogs SET title='${title}',content='${content}',createtime=${createtime} WHERE id=${id};`
  return exec(sql).then(updateData => {
    if (updateData.affectedRows > 0) {
      return true
    }
    return false
  })
}

// 删除博客
const deleteBlog = (id, author) => {
  const sql = `delete from blogs where id='${id}' and author='${author}';`
  return exec(sql).then(deleteData => {
    if (deleteData.affectedRows > 0) {
      return true
    }
    return false
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  deleteBlog
}